<template>
  <div class="app-container">
    <!-- 顶部统计卡片 -->
    <el-row :gutter="20" class="mb-4">
      <el-col :span="8">
        <el-card class="stats-card" shadow="hover">
          <div class="stats-value">{{ statsData?.normalCount || 0 }}</div>
          <div class="stats-label">正常电池</div>
          <el-icon class="stats-icon normal"><CircleCheckFilled /></el-icon>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="stats-card" shadow="hover">
          <div class="stats-value">{{ statsData?.warningCount || 0 }}</div>
          <div class="stats-label">告警电池</div>
          <el-icon class="stats-icon warning"><WarningFilled /></el-icon>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="stats-card" shadow="hover">
          <div class="stats-value">{{ statsData?.scrappedCount || 0 }}</div>
          <div class="stats-label">报废电池</div>
          <el-icon class="stats-icon danger"><CircleCloseFilled /></el-icon>
        </el-card>
      </el-col>
    </el-row>

    <!-- 在线电池和告警列表 -->
    <el-row :gutter="20" class="mb-4">
      <el-col :span="14">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>在线电池</span>
              <el-tag type="success">{{ onlineBatteries.length }} 个在线</el-tag>
            </div>
          </template>
          <el-table :data="onlineBatteries" height="300">
            <el-table-column type="index" label="序号" width="60" />
            <el-table-column prop="droneName" label="无人机" min-width="120" />
            <el-table-column prop="droneModel" label="无人机名称" min-width="120" />
            <el-table-column prop="batterySn" label="电池序列号" min-width="140" />
            <el-table-column prop="batteryModel" label="电池型号" min-width="100" />
            <el-table-column label="当前电量" min-width="180">
              <template #default="scope">
                <el-progress 
                  :percentage="Math.round((scope.row.currentCapacity / scope.row.capacity) * 100)"
                  :status="getBatteryStatus(scope.row.currentCapacity, scope.row.capacity)"
                />
              </template>
            </el-table-column>
            <el-table-column prop="cycleCount" label="循环次数" width="90" align="center" />
          </el-table>
          <pagination
            v-show="onlineTotal > 0"
            :total="onlineTotal"
            v-model:page="onlineQuery.pageNum"
            v-model:limit="onlineQuery.pageSize"
            @pagination="getOnlineBatteries"
          />
        </el-card>
      </el-col>
      
      <el-col :span="10">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>电池告警</span>
              <el-tag type="danger" v-if="alarmBatteries.length">{{ alarmBatteries.length }} 个告警</el-tag>
            </div>
          </template>
          <el-table :data="alarmBatteries" height="300">
            <el-table-column type="index" label="序号" width="60" />
            <el-table-column prop="batterySn" label="电池序列号" min-width="140" />
            <el-table-column prop="batteryModel" label="型号" min-width="100" />
            <el-table-column prop="cycleCount" label="循环次数" width="90" align="center" />
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- 统计图表 -->
    <el-row :gutter="20" class="mb-4">
      <el-col :span="12">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>电池状态分布</span>
            </div>
          </template>
          <div ref="pieChart" style="height: 300px"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>电池状态统计</span>
            </div>
          </template>
          <div ref="barChart" style="height: 300px"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 电池列表 -->
    <el-card shadow="hover">
      <template #header>
        <div class="card-header">
          <span>电池列表</span>
          <div class="header-operations">
            <el-input
              v-model="queryParams.batterySn"
              placeholder="请输入电池序列号"
              clearable
              style="width: 200px"
              class="mr-2"
              @keyup.enter="handleQuery"
            />
            <el-select v-model="queryParams.status" placeholder="电池状态" clearable style="width: 120px" class="mr-2">
              <el-option
                v-for="dict in health_state"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
            <el-button type="primary" @click="handleQuery">搜索</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </div>
        </div>
      </template>
      
      <el-table v-loading="loading" :data="batteryList">
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="batterySn" label="电池序列号" min-width="140" />
        <el-table-column prop="batteryModel" label="电池型号" min-width="100" />
        <el-table-column prop="lastDrone" label="最近搭载飞机" min-width="100" />
        <el-table-column prop="capacity" label="出场容量(mAh)" min-width="100" align="center" />
        <el-table-column prop="maxCycleCount" label="最大循环数" width="100" align="center" />
        <el-table-column prop="cycleCount" label="当前循环数" width="100" align="center" />
        <el-table-column label="状态" width="100" align="center">
          <template #default="scope">
            <dict-tag :options="health_state" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" align="center">
          <template #default="scope">
            <el-button
              v-if="scope.row.status !== '2'"
              type="text"
              size="small"
              @click="handleScrap(scope.row)"
            >报废</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import { ElMessageBox, ElMessage } from 'element-plus'
import { CircleCheckFilled, WarningFilled, CircleCloseFilled } from '@element-plus/icons-vue'
import { listBattery, getOnlineBattery, getAlarmBattery, scrapBattery, getBatteryStats } from '@/api/healthy/battery'
import { useDict } from "@/utils/dict.js";

const { health_state } = useDict('health_state')
const loading = ref(false)
const total = ref(0)
const onlineTotal = ref(0)
const batteryList = ref([])
const onlineBatteries = ref([])
const alarmBatteries = ref([])
const pieChart = ref(null)
const barChart = ref(null)
const statsData = ref({})
let charts = []

const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  batterySn: undefined,
  status: undefined
})

const onlineQuery = ref({
  pageNum: 1,
  pageSize: 10
})

// 获取电池列表
const getList = () => {
  loading.value = true
  listBattery(queryParams.value).then(res => {
    batteryList.value = res.rows
    total.value = res.total
    loading.value = false
  })
}

// 获取在线电池
const getOnlineBatteries = () => {
  getOnlineBattery(onlineQuery.value).then(res => {
    onlineBatteries.value = res.rows
    onlineTotal.value = res.total
  })
}

// 获取告警电池
const getAlarmBatteries = () => {
  getAlarmBattery().then(res => {
    alarmBatteries.value = res.data
  })
}

// 获取电池状态样式
const getBatteryStatus = (current, total) => {
  const percentage = (current / total) * 100
  if (percentage <= 20) return 'exception'
  if (percentage <= 50) return 'warning'
  return 'success'
}

// 初始化图表
const initCharts = () => {
  getBatteryStats().then(res => {
    statsData.value = res.data
    const { statusStats, statusCount } = res.data
    
    // 饼图
    const pie = echarts.init(pieChart.value)
    pie.setOption({
      title: {
        text: '当前系统内各状态电池比例'
      },
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c} ({d}%)'
      },
      series: [{
        type: 'pie',
        radius: ['50%', '70%'],
        data: statusStats?.map(item => ({
          name: health_state.value.find(dict => dict.value === item.status)?.label || item.status,
          value: item.value
        })) || []
      }]
    })
    charts.push(pie)

    // 横向条形图
    const bar = echarts.init(barChart.value)
    bar.setOption({
      title: {
        text: '当前系统内各状态电池数量'
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      xAxis: {
        type: 'value'
      },
      yAxis: {
        type: 'category',
        data: health_state.value.map(dict => dict.label)
      },
      series: [{
        type: 'bar',
        data: health_state.value.map(dict => {
          const stat = statusStats?.find(s => s.status === dict.value)
          return stat ? stat.value : 0
        })
      }]
    })
    charts.push(bar)
  })
}

// 报废处理
const handleScrap = (row) => {
  ElMessageBox.confirm(
    `是否确认报废电池序列号为"${row.batterySn}"的电池?`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    scrapBattery(row.id).then(() => {
      ElMessage.success('报废成功')
      getList()
      getOnlineBatteries()
      getAlarmBatteries()
      initCharts()
    })
  })
}

// 重置查询
const resetQuery = () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    batterySn: undefined,
    status: undefined
  }
  handleQuery()
}

// 查询操作
const handleQuery = () => {
  queryParams.value.pageNum = 1
  getList()
}

onMounted(() => {
  getList()
  getOnlineBatteries()
  getAlarmBatteries()
  initCharts()
})

onUnmounted(() => {
  charts.forEach(chart => {
    chart.dispose()
  })
})
</script>

<style scoped>
.app-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.mb-4 {
  margin-bottom: 20px;
}

.mr-2 {
  margin-right: 10px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-operations {
  display: flex;
  align-items: center;
}

.stats-card {
  position: relative;
  padding: 20px;
  height: 120px;
  overflow: hidden;
}

.stats-value {
  font-size: 32px;
  font-weight: bold;
  margin-bottom: 8px;
}

.stats-label {
  font-size: 16px;
  color: #606266;
}

.stats-icon {
  position: absolute;
  right: 20px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 48px;
  opacity: 0.2;
}

.stats-icon.normal {
  color: #67c23a;
}

.stats-icon.warning {
  color: #e6a23c;
}

.stats-icon.danger {
  color: #f56c6c;
}

:deep(.el-card__header) {
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
  background-color: #fafafa;
}

:deep(.el-card) {
  border-radius: 4px;
  border: none;
  box-shadow: 0 1px 4px rgba(0,21,41,.08) !important;
}

:deep(.el-table) {
  border-radius: 4px;
}
</style>